package diamondServer

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"server/Logic"
	"server/middleWare"
	"server/model"
	"server/response"
	"server/servers"
	"strconv"
)

func DiamondServer(port string) {
	r := gin.Default()
	r.Use(middleWare.CORS())

	r.GET("grandDown", func(ctx *gin.Context) {
		userid, _ := strconv.Atoi(ctx.Query("user_id"))
		depth, _ := strconv.Atoi(ctx.Query("depth"))
		depth, err := Logic.AddDepth(depth, userid)
		if err != nil {
			panic(err)
		}

		var diamonds [7][5]model.DiamondP
		if servers.Svc.DiamondModel.PdNextGrand(depth, userid) {
			diamonds, _ = Logic.GetAPageOfGrand(depth, userid, ctx)
		} else {

			err = Logic.CreateAPageOfGrand(depth, userid, ctx)
			if err != nil {
				response.Fail(ctx, nil, "创建方块失败")
			}
			diamonds, _ = Logic.GetAPageOfGrand(depth, userid, ctx)

		}
		response.Success(ctx, gin.H{"diamonds": diamonds}, "信息获取成功")
	})
	r.GET("grandUp", func(ctx *gin.Context) {
		userid, _ := strconv.Atoi(ctx.Query("user_id"))
		depth, _ := strconv.Atoi(ctx.Query("depth"))
		depth, err := Logic.DecreaseDepth(depth, userid)
		if err != nil {
			panic(err)
		}
		var diamonds [7][5]model.DiamondP
		diamonds, _ = Logic.GetAPageOfGrand(depth, userid, ctx)
		response.Success(ctx, gin.H{"diamonds": diamonds}, "信息获取成功")
	})

	r.GET("localGrand", func(ctx *gin.Context) {
		userid, _ := strconv.Atoi(ctx.Query("user_id"))
		depth, _ := strconv.Atoi(ctx.Query("depth"))
		var diamonds [7][5]model.DiamondP
		diamonds, _ = Logic.GetAPageOfGrand(depth, userid, ctx)
		response.Success(ctx, gin.H{"diamonds": diamonds}, "信息获取成功")
	})

	r.GET("getOneDiamondInfo", func(ctx *gin.Context) {
		userid, _ := strconv.Atoi(ctx.Query("user_id"))
		depth, _ := strconv.Atoi(ctx.Query("depth"))
		position, _ := strconv.Atoi(ctx.Query("position"))

		diamond, err := servers.Svc.DiamondModel.SelectOnlyOneDia(depth, userid, position)
		if err != nil {
			fmt.Println(err)
			response.Fail(ctx, nil, "单个方块查询出现问题")
		}
		response.Success(ctx, gin.H{"diamond": diamond}, "单个方块获取成功")
	})

	r.GET("updateDiamondInfoAfterDig", func(ctx *gin.Context) {
		diamondId, _ := strconv.Atoi(ctx.Query("diamond_id"))
		diamondState, _ := strconv.Atoi(ctx.Query("diamond_state"))
		number, _ := strconv.Atoi(ctx.Query("number"))

		err := servers.Svc.DiamondModel.UpdateOneByDiaId(diamondId, diamondState, number, 0)

		if err != nil {
			response.Fail(ctx, nil, "方块更新出现问题")
		}
		response.Success(ctx, nil, "方块更新成功")
	})

	r.Run(":" + port)
}
